// 类GomokuGame的成员如下：
// - mode: 游戏模式（'ai', 'local', 'online', 'watch'）
// - aiLevel: AI难度（'easy','medium','hard'）
// - playerColor: 玩家颜色（'black','white'）
// - roomId: 房间ID（联机模式使用）
// - boardSize: 棋盘大小，固定为15
// - board: 二维数组，表示棋盘状态（0:空,1:黑,2:白）
// - currentPlayer: 当前玩家（1:黑棋,2:白棋）
// - gameOver: 游戏是否结束
// - winner: 胜利者（1,2,0平局,null未结束）
// - moves: 走棋记录数组，每个元素为{x, y, player}
// - lastMove: 最后一步棋，{x,y} 或 null
class GomokuGame {
    constructor() {
        // 解析URL参数
        const params = new URLSearchParams(window.location.search);
        this.mode = params.get('mode') || 'ai';
        this.aiLevel = params.get('level') || 'medium';
        this.playerColor = params.get('color') || 'black';
        this.roomId = params.get('room') || null;

        // 处理随机颜色
        if (this.playerColor === 'random') {
            this.playerColor = Math.random() < 0.5 ? 'black' : 'white';
        }

        // 游戏状态
        this.boardSize = 15;
        this.board = Array(this.boardSize).fill().map(() => Array(this.boardSize).fill(0));
        this.currentPlayer = 1; // 1: 黑棋, 2: 白棋
        this.gameOver = false;
        this.winner = null;
        this.moves = [];
        this.lastMove = null;

        // DOM元素
        this.canvas = document.getElementById('game-board');
        this.ctx = this.canvas.getContext('2d');
        this.gameStatus = document.getElementById('game-status');
        this.gameModeEl = document.getElementById('game-mode');
        this.aiInfoEl = document.getElementById('ai-info');
        this.aiLevelEl = document.getElementById('ai-level');
        this.aiColorEl = document.getElementById('ai-color');
        this.onlineInfoEl = document.getElementById('online-info');
        this.roomIdEl = document.getElementById('room-id');
        this.blackPlayerEl = document.getElementById('black-player');
        this.whitePlayerEl = document.getElementById('white-player');

        // 初始化
        this.initUI();
        this.handleResize();
        this.drawBoard();
        this.setupEventListeners();

        // 窗口大小变化监听
        window.addEventListener('resize', () => this.handleResize());

        // 如果是AI模式且AI先手，则AI下棋
        if (this.mode === 'ai' && this.playerColor === 'white') {
            setTimeout(() => this.aiMove(), 500);
        }
    }

    initUI() {
        // 设置游戏模式显示
        const modeNames = {
            'ai': '人机对战',
            'local': '本地双人',
            'online': '联机对战',
            'watch': '观战模式'
        };
        this.gameModeEl.textContent = modeNames[this.mode] || this.mode;

        // 设置AI信息
        if (this.mode === 'ai') {
            this.aiInfoEl.classList.remove('d-none');
            const levelNames = {
                'easy': '简单',
                'medium': '中等',
                'hard': '困难'
            };
            this.aiLevelEl.textContent = levelNames[this.aiLevel] || this.aiLevel;
            this.aiColorEl.textContent = this.playerColor === 'black' ? '白棋' : '黑棋';
            this.blackPlayerEl.textContent = this.playerColor === 'black' ? '你' : 'AI';
            this.whitePlayerEl.textContent = this.playerColor === 'white' ? '你' : 'AI';
        } else if (this.mode === 'online') {
            this.onlineInfoEl.classList.remove('d-none');
            this.roomIdEl.textContent = this.roomId || '随机房间';
            this.blackPlayerEl.textContent = '玩家1';
            this.whitePlayerEl.textContent = '玩家2';
        } else {
            this.blackPlayerEl.textContent = '玩家1';
            this.whitePlayerEl.textContent = '玩家2';
        }
    }

    handleResize() {
        const container = this.canvas.parentElement;
        const size = Math.min(container.clientWidth, container.clientHeight, 600);

        // 设置canvas的显示尺寸
        this.canvas.style.width = `${size}px`;
        this.canvas.style.height = `${size}px`;

        // 设置canvas的位图尺寸（考虑设备像素比）
        const scale = window.devicePixelRatio || 1;
        this.canvas.width = size * scale;
        this.canvas.height = size * scale;
        this.ctx.scale(scale, scale);

        // 重绘棋盘
        this.drawBoard();
    }

    drawBoard() {
        const ctx = this.ctx;
        const size = parseInt(this.canvas.style.width);
        const cellSize = size / (this.boardSize + 1);

        // 清空画布
        ctx.clearRect(0, 0, size, size);

        // 绘制棋盘背景
        ctx.fillStyle = '#e6c88c';
        ctx.fillRect(0, 0, size, size);

        // 绘制网格线
        ctx.strokeStyle = '#000';
        ctx.lineWidth = 1;

        for (let i = 0; i < this.boardSize; i++) {
            // 横线
            ctx.beginPath();
            ctx.moveTo(cellSize, cellSize * (i + 1));
            ctx.lineTo(cellSize * this.boardSize, cellSize * (i + 1));
            ctx.stroke();

            // 竖线
            ctx.beginPath();
            ctx.moveTo(cellSize * (i + 1), cellSize);
            ctx.lineTo(cellSize * (i + 1), cellSize * this.boardSize);
            ctx.stroke();
        }

        // 绘制天元和星位
        const starPoints = [3, 7, 11];
        ctx.fillStyle = '#000';

        starPoints.forEach(x => {
            starPoints.forEach(y => {
                ctx.beginPath();
                ctx.arc(
                    cellSize * (x + 1), 
                    cellSize * (y + 1), 
                    cellSize * 0.1, 
                    0, 
                    Math.PI * 2
                );
                ctx.fill();
            });
        });

        // 绘制已有棋子
        for (let y = 0; y < this.boardSize; y++) {
            for (let x = 0; x < this.boardSize; x++) {
                if (this.board[y][x] !== 0) {
                    this.drawPiece(x, y, this.board[y][x], cellSize);
                }
            }
        }

        // 标记最后一步
        if (this.lastMove) {
            this.markLastMove(this.lastMove.x, this.lastMove.y, cellSize);
        }
    }

    drawPiece(x, y, player, cellSize) {
        const centerX = cellSize * (x + 1);
        const centerY = cellSize * (y + 1);
        const radius = cellSize * 0.45;

        const gradient = this.ctx.createRadialGradient(
            centerX - radius * 0.3, 
            centerY - radius * 0.3, 
            radius * 0.1, 
            centerX, 
            centerY, 
            radius
        );

        if (player === 1) { // 黑棋
            gradient.addColorStop(0, '#666');
            gradient.addColorStop(1, '#000');
        } else { // 白棋
            gradient.addColorStop(0, '#fff');
            gradient.addColorStop(1, '#ddd');
        }

        this.ctx.fillStyle = gradient;
        this.ctx.beginPath();
        this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
        this.ctx.fill();
    }

    markLastMove(x, y, cellSize) {
        const centerX = cellSize * (x + 1);
        const centerY = cellSize * (y + 1);
        const radius = cellSize * 0.1;

        this.ctx.fillStyle = '#f00';
        this.ctx.beginPath();
        this.ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
        this.ctx.fill();
    }

    setupEventListeners() {
        // 棋盘点击事件
        this.canvas.addEventListener('click', (e) => this.handleClick(e));
        // moveHistory.push({row: row, col: col, player: currentPlayer});
        // 触摸事件支持
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            const mouseEvent = new MouseEvent('click', {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            this.canvas.dispatchEvent(mouseEvent);
        }, { passive: false });

        // 按钮事件
        document.getElementById('undo-btn').addEventListener('click', ()=>{
            if(confirm('确定要悔棋吗？')){
                this.handleUndo();
            }
        });

        document.getElementById('back-btn').addEventListener('click', () => {
            if (this.gameOver || confirm('游戏尚未结束，确定要返回大厅吗？')) {
                this.returnToLobby();
            }
        });

        document.getElementById('restart-btn').addEventListener('click', () => {
            if (confirm('确定要重新开始游戏吗？')) {
                this.resetGame();
            }
        });

        document.getElementById('surrender-btn').addEventListener('click', () => {
            if (confirm('确定要认输吗？')) {
                this.endGame(this.currentPlayer === 1 ? 2 : 1);
            }
        });

        document.getElementById('playAgainBtn').addEventListener('click', () => {
            this.resetGame();
            bootstrap.Modal.getInstance(document.getElementById('gameOverModal')).hide();
        });

        document.getElementById('returnToLobbyBtn').addEventListener('click', () => {
            this.returnToLobby();
        });
    }

    handleClick(e) {
        if (this.gameOver) return;

        // 如果是AI模式且不是玩家回合，则忽略点击
        if (this.mode === 'ai') {
            const isPlayerTurn = 
                (this.currentPlayer === 1 && this.playerColor === 'black') || 
                (this.currentPlayer === 2 && this.playerColor === 'white');
            if (!isPlayerTurn) return;
        }

        // 计算点击的棋盘坐标
        const rect = this.canvas.getBoundingClientRect();
        const size = parseInt(this.canvas.style.width);
        const cellSize = size / (this.boardSize + 1);

        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        const boardX = Math.round(x / cellSize) - 1;
        const boardY = Math.round(y / cellSize) - 1;

        // 检查是否有效落子
        if (boardX >= 0 && boardX < this.boardSize && 
            boardY >= 0 && boardY < this.boardSize && 
            this.board[boardY][boardX] === 0) {
            
            this.makeMove(boardX, boardY);
        }
    }

    makeMove(x, y) {
        // 落子
        this.board[y][x] = this.currentPlayer;
        this.moves.push({x, y, player: this.currentPlayer});
        this.lastMove = {x, y};

        // 重绘棋盘
        const size = parseInt(this.canvas.style.width);
        const cellSize = size / (this.boardSize + 1);
        this.drawBoard();

        // 检查胜利
        if (this.checkWin(x, y)) {
            this.endGame(this.currentPlayer);
            return;
        }

        // 检查平局
        if (this.moves.length === this.boardSize * this.boardSize) {
            this.endGame(0);
            return;
        }

        // 切换玩家
        this.currentPlayer = this.currentPlayer === 1 ? 2 : 1;
        this.updateGameStatus();

        // 如果是AI模式且轮到AI，则AI下棋
        if (this.mode === 'ai') {
            const isAiTurn = 
                (this.currentPlayer === 1 && this.playerColor === 'white') || 
                (this.currentPlayer === 2 && this.playerColor === 'black');
            if (isAiTurn) {
                setTimeout(() => this.aiMove(), 500);
            }
        }
    }

    checkWin(x, y) {
        const directions = [
            [1, 0], [0, 1], [1, 1], [1, -1]
        ];

        const player = this.board[y][x];

        for (const [dx, dy] of directions) {
            let count = 1;

            // 正向检查
            for (let i = 1; i < 5; i++) {
                const nx = x + dx * i;
                const ny = y + dy * i;

                if (nx < 0 || nx >= this.boardSize || 
                    ny < 0 || ny >= this.boardSize || 
                    this.board[ny][nx] !== player) {
                    break;
                }
                count++;
            }

            // 反向检查
            for (let i = 1; i < 5; i++) {
                const nx = x - dx * i;
                const ny = y - dy * i;

                if (nx < 0 || nx >= this.boardSize || 
                    ny < 0 || ny >= this.boardSize || 
                    this.board[ny][nx] !== player) {
                    break;
                }
                count++;
            }

            if (count >= 5) {
                return true;
            }
        }

        return false;
    }

    updateGameStatus() {
        const playerNames = {
            1: '黑方',
            2: '白方'
        };
        this.gameStatus.textContent = `${playerNames[this.currentPlayer]}回合`;
        this.gameStatus.className = `alert alert-${this.currentPlayer === 1 ? 'dark' : 'light'}`;
    }

    aiMove() {
        if (this.gameOver) return;

        let x, y;

        switch (this.aiLevel) {
            case 'easy':
                [x, y] = this.getRandomMove();
                break;
            case 'medium':
                [x, y] = this.getSmartMove();
                break;
            case 'hard':
                [x, y] = this.getBestMove();
                break;
            default:
                [x, y] = this.getRandomMove();
        }

        this.makeMove(x, y);
    }

    getRandomMove() {
        const emptyCells = [];

        for (let y = 0; y < this.boardSize; y++) {
            for (let x = 0; x < this.boardSize; x++) {
                if (this.board[y][x] === 0) {
                    emptyCells.push({x, y});
                }
            }
        }

        if (emptyCells.length === 0) return [0, 0];

        const randomIndex = Math.floor(Math.random() * emptyCells.length);
        return [emptyCells[randomIndex].x, emptyCells[randomIndex].y];
    }

    getSmartMove() {
        const scores = Array(this.boardSize).fill().map(() => Array(this.boardSize).fill(0));
        const aiPlayer = this.currentPlayer;
        const humanPlayer = aiPlayer === 1 ? 2 : 1;

        for (let y = 0; y < this.boardSize; y++) {
            for (let x = 0; x < this.boardSize; x++) {
                if (this.board[y][x] !== 0) continue;
                scores[y][x] = this.evaluatePosition(x, y, aiPlayer, humanPlayer);
            }
        }

        let maxScore = -1;
        let bestMoves = [];

        for (let y = 0; y < this.boardSize; y++) {
            for (let x = 0; x < this.boardSize; x++) {
                if (this.board[y][x] !== 0) continue;

                if (scores[y][x] > maxScore) {
                    maxScore = scores[y][x];
                    bestMoves = [{x, y}];
                } else if (scores[y][x] === maxScore) {
                    bestMoves.push({x, y});
                }
            }
        }

        if (bestMoves.length > 0) {
            const randomIndex = Math.floor(Math.random() * bestMoves.length);
            return [bestMoves[randomIndex].x, bestMoves[randomIndex].y];
        }

        return this.getRandomMove();
    }

    evaluatePosition(x, y, aiPlayer, humanPlayer) {
        let score = 0;
        const directions = [
            [1, 0], [0, 1], [1, 1], [1, -1]
        ];

        for (const [dx, dy] of directions) {
            let aiCount = this.countPotential(x, y, dx, dy, aiPlayer);
            let humanCount = this.countPotential(x, y, dx, dy, humanPlayer);

            if (aiCount >= 4) score += 1000;
            else if (aiCount === 3) score += 100;
            else if (aiCount === 2) score += 10;

            if (humanCount >= 4) score += 500;
            else if (humanCount === 3) score += 50;
            else if (humanCount === 2) score += 5;
        }

        // 中心位置加分
        const center = this.boardSize / 2;
        const distanceToCenter = Math.sqrt(Math.pow(x - center, 2) + Math.pow(y - center, 2));
        score += (this.boardSize - distanceToCenter) * 0.1;

        return score;
    }

    countPotential(x, y, dx, dy, player) {
        let count = 0;

        // 正向检查
        for (let i = 1; i < 5; i++) {
            const nx = x + dx * i;
            const ny = y + dy * i;

            if (nx < 0 || nx >= this.boardSize || ny < 0 || ny >= this.boardSize) {
                break;
            }

            if (this.board[ny][nx] === player || (nx === x && ny === y)) {
                count++;
            } else if (this.board[ny][nx] !== 0) {
                count = 0;
                break;
            }
        }

        // 反向检查
        for (let i = 1; i < 5; i++) {
            const nx = x - dx * i;
            const ny = y - dy * i;

            if (nx < 0 || nx >= this.boardSize || ny < 0 || ny >= this.boardSize) {
                break;
            }

            if (this.board[ny][nx] === player || (nx === x && ny === y)) {
                count++;
            } else if (this.board[ny][nx] !== 0) {
                count = 0;
                break;
            }
        }

        return count >= 5 ? 5 : count;
    }

    getBestMove() {
        // 更复杂的AI策略可以在这里实现
        return this.getSmartMove();
    }

    endGame(winner) {
        this.gameOver = true;
        this.winner = winner;

        // 保存对战记录
        this.saveGameRecord(winner);

        const modal = new bootstrap.Modal(document.getElementById('gameOverModal'));
        const title = document.getElementById('gameOverTitle');
        const message = document.getElementById('gameOverMessage');

        if (winner === 0) {
            title.textContent = '游戏结束 - 平局';
            message.innerHTML = '<div class="alert alert-secondary">本局比赛双方势均力敌！</div>';
        } else {
            const winnerName = winner === 1 ? '黑方' : '白方';
            title.textContent = '游戏结束 - 胜负已分';
            message.innerHTML = `<div class="alert alert-${winner === 1 ? 'dark' : 'light'}">恭喜${winnerName}获得胜利！</div>`;
        }

        // 添加自动返回倒计时
        let countdown = 10;
        const countdownEl = document.createElement('div');
        countdownEl.className = 'mt-2 text-muted small';
        message.appendChild(countdownEl);
        
        const timer = setInterval(() => {
            countdownEl.textContent = `${countdown}秒后自动返回大厅...`;
            countdown--;
            
            if (countdown < 0) {
                clearInterval(timer);
                this.returnToLobby();
            }
        }, 1000);

        modal.show();

        // 修改按钮事件
        document.getElementById('playAgainBtn').onclick = () => {
            clearInterval(timer);
            this.resetGame();
            modal.hide();
        };
    }

    saveGameRecord(winner) {
        if (winner === null) return;

        let result, opponent;
        
        switch(this.mode) {
            case 'ai':
                result = (winner === 0) ? '平局' : 
                        ((winner === 1 && this.playerColor === 'black') || 
                         (winner === 2 && this.playerColor === 'white')) ? '胜利' : '失败';
                opponent = '电脑';
                break;
            case 'local':
                result = (winner === 0) ? '平局' : 
                        (winner === 1) ? '玩家1胜利' : '玩家2胜利';
                opponent = '本地玩家';
                break;
            case 'online':
                result = (winner === 0) ? '平局' : 
                        (winner === 1) ? '胜利' : '失败';
                opponent = '在线玩家';
                break;
            default:
                return;
        }

        // 获取当前用户
        const currentUser = JSON.parse(localStorage.getItem('gomoku_currentUser')) || {
            username: '游客',
            isGuest: true,
            token: 'guest_' + Math.random().toString(36).slice(2, 9)
        };

        // 添加到对战记录
        const records = JSON.parse(localStorage.getItem('gomoku_records')) || [];
        records.unshift({
            id: 'rec_' + Math.random().toString(36).slice(2, 9),
            mode: this.mode,
            result: result,
            opponent: opponent,
            timestamp: new Date().toISOString(),
            aiLevel: this.mode === 'ai' ? this.aiLevel : false,
            userId: currentUser.token,
            username: currentUser.username
        });
        
        localStorage.setItem('gomoku_records', JSON.stringify(records));
    }

    handleUndo() {
        if (this.gameOver) {
            return; // 游戏结束不能悔棋
        }

        // 本地对战模式：只悔一步（最后一步）
        if (this.mode === 'local') {
            if (this.moves.length > 0) {
                // 弹出最后一步
                const move = this.moves.pop();
                // 重置该位置
                this.board[move.y][move.x] = 0;

                // 设置当前玩家为被悔掉的那步棋的玩家（轮到该玩家重新下）
                this.currentPlayer = move.player;

                // 更新最后一步标记
                this.lastMove = this.moves.length > 0 ? this.moves[this.moves.length-1] : null;

                // 更新游戏状态
                this.gameOver = false;
                this.winner = null;
                this.drawBoard();
                this.updateGameStatus();
            }
            return;
        }

        // AI模式：根据对方是否下棋决定悔一步或两步
        const opponent = this.currentPlayer === 1 ? 2 : 1;
        const n = this.moves.length;

        let steps = 0;
        // 情况1: 当前轮到对手（对方未下棋）-> 悔一步（自己最后一步）
        if (this.currentPlayer === opponent) {
            if (n > 0 && this.moves[n-1].player !== this.currentPlayer) {
                steps = 1;
            }
        } 
        // 情况2: 当前轮到自己（对方已下棋）-> 悔两步
        else if (this.currentPlayer !== opponent) {
            if (n >= 2 && this.moves[n-1].player === opponent && this.moves[n-2].player !== opponent) {
                steps = 2;
            }
        }

        if (steps === 0) {
            return; // 不符合悔棋条件
        }

        // 执行悔棋操作
        for (let i = 0; i < steps; i++) {
            const move = this.moves.pop();
            this.board[move.y][move.x] = 0; // 重置棋盘位置
        }

        // 更新最后一步
        this.lastMove = this.moves.length > 0 ? this.moves[this.moves.length-1] : null;

        // 更新游戏状态
        this.gameOver = false;
        this.winner = null;
        this.drawBoard();
        this.updateGameStatus();
    }

    returnToLobby() {
        document.body.style.opacity = '0.7';
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 300);
    }

    resetGame() {
        this.board = Array(this.boardSize).fill().map(() => Array(this.boardSize).fill(0));
        this.currentPlayer = 1;
        this.gameOver = false;
        this.winner = null;
        this.moves = [];
        this.lastMove = null;

        this.drawBoard();
        this.updateGameStatus();

        if (this.mode === 'ai' && this.playerColor === 'white') {
            setTimeout(() => this.aiMove(), 500);
        }
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new GomokuGame();
});